package pers.cz.selenium.component;

import org.openqa.selenium.Alert;
import org.openqa.selenium.remote.RemoteWebDriver;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import pers.cz.thread.ThreadUtils;
import pers.cz.websocket.MessagePushSocketUtils;

import java.util.Set;

/**
 * @program: PostGirl-panent
 * @description: 主框架控件,随着切换变化
 * @author: Cheng Zhi
 * @create: 2022-12-27 17:41
 **/
public class ContextComponent{

    private Logger logger = LoggerFactory.getLogger(ContextComponent.class);
    private RemoteWebDriver driver;

    public ContextComponent(RemoteWebDriver driver) {
        this.driver = driver;
    }

    /**
     * 判断当前页面是否有弹框
     * @return
     */
    public boolean isHaveAlert() {

        boolean flag = false;
        try {
            Alert alert = driver.switchTo().alert();
            flag = true;
        } catch (Exception e) {
        }

        return flag;
    }

    public void closeAlert() {

        try {
            Alert alert = driver.switchTo().alert();
            String text = alert.getText();
            MessagePushSocketUtils.sendMsg( MessagePushSocketUtils.AUTOUI_LOG_MESSAGE, text, 0);
        } catch (Exception e) {
            MessagePushSocketUtils.sendMsg( MessagePushSocketUtils.AUTOUI_LOG_MESSAGE, "没有找到提示框", 0);
        }
    }

    public boolean switchNewIframe() {
        // todo 待实现
        return true;
    }
    /**
     * 切换到新窗口
     * @return
     */
    public boolean switchNewWin() {

        try {
            ThreadUtils.doSleep(5000L);
            if (isHaveAlert()) {
                // 把弹框点掉
                driver.switchTo().alert().accept();
            }
            String lastHandle = null;
            for (String handle : driver.getWindowHandles()) {
                lastHandle = handle;
            }
            driver.switchTo().window(lastHandle);
            return true;
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return false;
        }
    }

    /**
     * 获取网页源码
     * @return
     */
    public String getSource() {
        String pageSource = driver.getPageSource();
        return pageSource;
    }

    /**
     * 获取当前路径
     * @return
     */
    public String getCurrentUrl() {
        String currentUrl = driver.getCurrentUrl();
        return currentUrl;
    }

}
